﻿using System.Linq;
using Microsoft.Win32;

namespace MLogix
{
    sealed class InterceptorControl
    {
        const string GUID = "{816774E0-D8C7-4d13-8011-29AFEDBA4DB2}";
        static RegistryKey clsidCheck = Registry.ClassesRoot.OpenSubKey("CLSID",true);
        static RegistryKey interceptorCheck = Registry.LocalMachine.CreateSubKey("Software").CreateSubKey("Microsoft").CreateSubKey("Inbox").CreateSubKey("Svc").OpenSubKey("SMS",true);
        static RegistryKey clsidReg = Registry.ClassesRoot.CreateSubKey("CLSID").CreateSubKey(GUID).CreateSubKey("InProcServer32");
        static RegistryKey interceptorReg = Registry.LocalMachine.CreateSubKey("Software").CreateSubKey("Microsoft").CreateSubKey("Inbox").CreateSubKey("Svc").CreateSubKey("SMS").CreateSubKey("Rules");
        static RegistryKey rulesReg = Registry.CurrentUser.CreateSubKey("Software").CreateSubKey("MLogix").CreateSubKey("Rules");
        static internal void ClearInterceptor()
        {
            if (interceptorReg.ValueCount > 0)
                interceptorReg.DeleteValue(GUID,false);
            if (clsidReg.ValueCount > 0)
                clsidReg.DeleteValue("",false);
            clsidReg.Flush();
            interceptorReg.Flush();
        }

        static internal void StartInterceptor()
        {
            interceptorReg.SetValue(GUID, 1, RegistryValueKind.DWord);
            clsidReg.SetValue("", "mapirule.dll");
            clsidReg.Flush();
            interceptorReg.Flush();
        }

        static internal bool GetInterceptorStatus()
        {
            if (clsidReg.GetValueNames().Contains("Default"))
                if (interceptorReg.GetValueNames().Contains(GUID))
                    return true;
            ClearInterceptor();
            return false;
        }

        static internal void SaveFiltersToReg(string[] contacts, string[] messages)
        {
            string delimContactRules = string.Empty;
            string delimMessageRules = string.Empty;
            foreach (string cRule in contacts)
            {
                if (!string.IsNullOrEmpty(cRule))
                    delimContactRules += cRule + "|";
            }
            foreach (string mRule in messages)
            {
                if (!string.IsNullOrEmpty(mRule))
                    delimMessageRules += mRule + "|";
            }
             
            rulesReg.SetValue("ContactRules", delimContactRules);
            rulesReg.SetValue("MessageRules", delimMessageRules);
            rulesReg.Flush();
        }
        static internal void SetSaveAppRegPath()
        {
            rulesReg.SetValue("AppPath", Win32.location + "\\Saver.exe");
            rulesReg.Flush();
        }
    }
}
